<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <el-card>
    <el-alert title="添加商品信息" type="info" show-icon center :closable="false"/>

    <el-steps :active=" stepIndex - '0' " finish-status="success" style="margin-top: 50px;" align-center>
      <el-step title="基本信息"/>
      <el-step title="商品参数"/>
      <el-step title="商品属性"/>
      <el-step title="商品图片"/>
      <el-step title="商品内容"/>
      <el-step title="完成"/>
    </el-steps>

    <el-form
        ref="addFormRef"
        :model="addForm"
        status-icon
        :rules="addFormRules"
        label-width="120px"
        label-position="top"
    >
      <el-tabs tab-position="left"
               v-model="stepIndex"
               style="margin-left: 10px; margin-right: 10px; margin-top: 50px"
               :before-leave="beforeTabLeave"
               @tab-change="tabClicked"
      >
        <el-tab-pane label="基本信息" name="0">

          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"/>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"/>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight" type="number">
            <el-input v-model="addForm.goods_weight"/>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addForm.goods_number"/>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader v-model="addForm.goods_cat"
                         :options="cateList"
                         @change="handleChange"
                         :props="cateProps"
            />
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item :label="item.attr_name"
                        v-for="item in manyTableData"
                        :key="item.attr_id"
          >
            <div>
              <el-checkbox-group v-model="item.attr_vals" size="default">
                <el-checkbox :label="cb"
                             v-for="(cb, i) in item.attr_vals"
                             :key="i"
                             border style="margin-top: 15px"/>
              </el-checkbox-group>


            </div>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
            <el-input v-model="item.attr_vals"/>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload

              :action="uploadURL"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <div style="border: 1px solid #ccc">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
            />
          </div>
          <el-button @click="addGood" type="primary" style="margin-top: 15px">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>

    </el-form>


  </el-card>

  <el-dialog
      v-model="previewDialogVisble"
      title="图片预览"
      width="40%"
  >
    <img :src="previewPath" class="previewImg">
  </el-dialog>

</template>

<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import {onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

export default {
  name: "AddGoods",
  components: {Editor, Toolbar},
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    let valueHtml = ref('')

    // 模拟 ajax 异步获取内容
    onMounted(() => {

    })

    const toolbarConfig = {}
    const editorConfig = {placeholder: '请输入内容...'}

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  },
  computed: {
    cateId() {

      if (this.addForm.goods_cat.length !== 3) {
        return null
      } else {
        return this.addForm.goods_cat[2]
      }
    }
  },
  data() {
    return {
      stepIndex: '0',
      cateList: [],
      manyTableData: [],
      onlyTableData: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      previewPath: '',
      previewDialogVisble: false,
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 999999,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}

        ],
        goods_price: [
          {required: true, message: '请输入商品价格', trigger: 'blur'}

        ],
        goods_weight: [
          {required: true, message: '请输入商品重量', trigger: 'blur'}

        ],
        goods_number: [
          {required: true, message: '请输入商品数量', trigger: 'blur'}
        ],
        goods_cat: [
          {required: true, message: '请选择商品分类', trigger: 'blur'}
        ]
      },


    }
  },
  methods: {
    addGood() {
      this.addForm.goods_introduce = this.valueHtml
      this.$refs.addFormRef.validate(async v => {
        if (!v) {
          return this.$message.error("请填写必要的信息！")
        } else {
          // 发送网络请求

          const form = JSON.parse(JSON.stringify(this.addForm))

          form.goods_cat = form.goods_cat.join(',')


          this.manyTableData.forEach(e => {
            const tempInfo = {attr_id: e.attr_id, attr_value: e.attr_vals.join(' ')}
            this.addForm.attrs.push(tempInfo)
          })
          this.onlyTableData.forEach(e => {
            const tempInfo = {attr_id: e.attr_id, attr_value: e.attr_vals}
            this.addForm.attrs.push(tempInfo)
          })
          form.attrs = this.addForm.attrs

          const {data: res} = await this.$http.post(`/goods`, form)

          if (res.meta.status === 201) {
            this.$router.push('/goods')
          }

          return (res.meta.status === 201) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
        }
      })

      // console.log(this.valueHtml)
    },
    async getCateList() {
      const {data: res} = await this.$http.get(`/categories`)
      if (res.meta.status === 200) {
        this.cateList = res.data
      }
      return (res.meta.status === 200) ? null : this.$message.error(res.meta.msg);
    },
    async handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return this.$message.error('无法选择该选项')
      } else {
        await this.getCateList()
      }
      // console.log(this.addForm.goods_cat)
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0') {
        if (this.addForm.goods_cat.length !== 3) {
          this.$message.error("请先选择商品分类")
          return false;
        }
      }
      return true;
      // let validateFieldArray = ['goods_name', 'goods_price', 'goods_weight', 'goods_number'];
      // this.window.sessionStorage.setItem('flag', 'true')
      // let addFormRef = this.$refs.addFormRef;
      //
      // validateFieldArray.forEach(function (e){
      //   addFormRef.validateField(e, (val) => {
      //     // if(val === false){
      //     //   this.window.sessionStorage.setItem('flag', e)
      //     // }
      //   })
      // })

      // let flag = this.window.sessionStorage.getItem('flag')
      // console.log(flag)

      // if(flag){
      //   this.$message.error("您必须准确填写好当前内容，才可以进入下一步！")
      // }

      // return flag;
    },
    async tabClicked() {
      if (this.stepIndex === '1') {
        const {data: res} = await this.$http.get(`/categories/${this.cateId}/attributes`,
            {
              params: {sel: 'many'}
            }
        )
        // console.log(res)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? null : item.attr_vals.split(',')
          console.log(item.attr_vals)
        })

        this.manyTableData = res.data
      } else if (this.stepIndex === '2') {
        const {data: res} = await this.$http.get(`/categories/${this.cateId}/attributes`,
            {
              params: {sel: 'only'}
            }
        )

        this.onlyTableData = res.data
        console.log(res.data)
      }

    },
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewDialogVisble = true
    },
    handleRemove(file) {
      const filePath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(e => e.pic === filePath)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm)
    },
    handleSuccess(resp) {

      const picInfo = {pic: resp.data.tmp_path}
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    }
  },
  created() {
    this.getCateList()
  },

}

</script>

<style scoped>
.previewImg {
  width: 100%;
}
</style>